﻿using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZK.Common
{
    public class QRCodeNet
    {
        /// <summary>
        /// 设置二维码大小
        /// </summary>
        public static Image Generate(string str)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = qrEncoder.Encode(str);
            //ModuleSize 设置图片大小  
            //QuietZoneModules 设置周边padding
            /*
                * 5----150*150    padding:5
                * 10----300*300   padding:10
                */
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(3, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            Point padding = new Point(MM2Inch(1), MM2Inch(1));
            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap map = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics g = Graphics.FromImage(map);
            render.Draw(g, qrCode.Matrix, padding);
            return map;
        }

        /// <summary>
        /// 转换毫米到百分之一英寸
        /// </summary>
        /// <param name="mm"></param>
        /// <returns></returns>
        private static int MM2Inch(double mm)
        {
            return (int)(mm * 100.0f / 25.4f);
        }

        /// <summary>
        /// 生成带Logo的二维码
        /// </summary>
        //public static void Generate5()
        //{
        //    string str = url;
        //    QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
        //    QrCode qrCode = qrEncoder.Encode(str);
        //    //保存成png文件
        //    string fileName = Guid.NewGuid().ToString();
        //    string filename = fileName + ".png";
        //    GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

        //    DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
        //    Bitmap map = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
        //    Graphics g = Graphics.FromImage(map);
        //    render.Draw(g, qrCode.Matrix);
        //    //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
        //    Image img = Image.FromFile("c#.jpg");
        //    int w = 40;
        //    Point imgPoint = new Point((map.Width - w) / 2, (map.Height - w) / 2);
        //    //Point imgPoint = new Point(10, 10);
        //    //logo 的位置和宽高
        //    g.DrawImage(img, imgPoint.X, imgPoint.Y, w, w);
        //    map.Save(filename, ImageFormat.Png);
        //}
    }
}
